﻿using AutoMapper;
using Dapper;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Implement;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Read.Apis.Application.Command.DepartMentes;
using Management.Systeam.Read.Apis.Application.Command.ProductOutAllows;
using MediatR;
using System.Text;

namespace Management.Systeam.Read.Apis.Application.CommandHandler.ProductOutAllows
{
    public class ShowProductOutAllowCommandHandler : IRequestHandler<ShowProductOutAllowCommand, ApiPeaging<ApiResult<List<ProductOutAllow>>>>
    {
        IBaseRepository<ProductOutAllow> ProductOutAllow;
        IMapper mapper;
        DatabaseContext db;
        public ShowProductOutAllowCommandHandler(IBaseRepository<ProductOutAllow> ProductOutAllow, IMapper mapper,DatabaseContext db)
        {
            this.ProductOutAllow = ProductOutAllow;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<ApiPeaging<ApiResult<List<ProductOutAllow>>>> Handle(ShowProductOutAllowCommand request, CancellationToken cancellationToken)
        {   
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT * FROM ProductOutAllow");
            sb.Append(" WHERE IsDel LIKE '%" + 0 + "%'");
            if (request.Product_Name != null)
            {
                sb.Append(" AND Product_Name LIKE '%" + request.Product_Name + "%'");
            }
            if (request.Product_Code != null)
            {
                sb.Append(" AND Product_Code LIKE '%" + request.Product_Code + "%'");
            }
            var paramet = new
            {
                Product_Name = request.Product_Name,
                Product_Code = request.Product_Code,
                PageSize = request.PageSize,
                offset = (request.PageIndex - 1) * request.PageSize
            };
            var qtlist = await db.DapperConnection.QueryAsync<Resources>(sb.ToString(), paramet);
            int total = qtlist.Count();
            sb.Append(" ORDER BY Product_Id DESC LIMIT @PageSize OFFSET @offset");
      
            var pageData = await db.DapperConnection.QueryAsync<ProductOutAllow>(sb.ToString(), paramet);
            int totalPage = (int)Math.Ceiling(total / (double)request.PageSize);

            return new ApiPeaging<ApiResult<List<ProductOutAllow>>>
            {
                Total = total,
                TotalPage = totalPage,
                Data = new ApiResult<List<ProductOutAllow>>
                {
                    Code = ApiEnum.success,
                    Message = "查询成功",
                    Data = pageData.ToList()
                }
            };

        }
    }
}
